'use strict';
const jwt = require('jsonwebtoken');
const crypto = require('crypto');

module.exports = app => {

  return class TokenService extends app.Service {
    /**
     * @description 创建token
     * @param {Object} userinfo 用户信息
     * @return 返回token
     */
    createToken(tokenInfo) {
      const result = jwt.sign(tokenInfo, app.config.jwtSecret, { expiresIn: '7d' });
      return result;
    }

    /**
     * @description 验证票据
     * @param {Object} token 用户请求token
     * @return 返回 错误或者解密过的token
     */
    verifyToken(token) {
      if (token) {
        try {
          const result = jwt.verify(token, app.config.jwtSecret);
          return { isSuccess: true, result };
        } catch (err) {
                // token过期
          if (err.name === 'TokenExpiredError') {
            return { isSuccess: false, msg: 'token过期' };
          }
        }
      }
      return { isSuccess: false, msg: 'please provide valid token!' };
    }
  };
};
